//https://blog.csdn.net/zl1zl2zl3/article/details/81357146
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import {
    Row,
    Col,
    Card,
    Form,
    Input,
    Icon,
    Button,
    message,
} from 'antd';
//import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from './ProTabColumnAuthList.less';

import TableColumnAuthModel from './ProAssignTabColumnByAuth';//分配模型列
import StandardTableAuth from './ProAuthList';//角色列表
import StandardTableColumn from './ProTabColumnList';//模型列表

import {getValue} from '@/utils/globalcommon';
const FormItem = Form.Item;



/* eslint react/no-multi-comp:0 */
@connect(({ protabcolumnauth, loading }) => ({
    protabcolumnauth,
    loading: loading.models.protabcolumnauth,
}))

@Form.create()
class ProTableColumnAuthList extends PureComponent {
    state = {
        modalVisible: false,
        updateModalVisible: false,
        viewModalVisible: false,
        tableColumnAuthVisible: false,
        expandForm: false,
        selectedRows: [],
        formValues: {},
        updateFormValues: {},
        viewFormValues: {},
        authId: [],
        pageByauthId: "",
    };

    columnsAuth = [

        {
        	title: '角色名称',
        	dataIndex: 'auth_name',
        },        
        {
	        title: '角色类型',
	        dataIndex: 'auth_type',
        },
	];
	
    columnsTable = [
        {
        	title: '名称',
       	 	dataIndex: 'tablename',
        },        
        {
        	title: '列名称',
        	dataIndex: 'columnname',
        },
        {
        	title: '列类型',
        	dataIndex: 'columntype',
        },
	];

componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
        type: 'protabcolumnauth/query_page_for_proauthority',
    });
}

handleStandardTableChangeAuth = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { pageByauthId } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
        const newObj = { ...obj };
    newObj[key] = getValue(filtersArg[key]);
    return newObj;
}, {});

    const params = {
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
        ...formValues,
        ...filters,
    };
    if (sorter.field) {
        params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
        type: 'protabcolumnauth/query_page_for_proauthority',
        payload: params,
    });
};

handleStandardTableChangeTableColumn = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues,authId } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
        const newObj = { ...obj };
	    newObj[key] = getValue(filtersArg[key]);
	    return newObj;
	}, {});

    const params = {
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
        ...formValues,
        ...filters,
        auth_id: authId,
    };
    if (sorter.field) {
        params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
        type: 'protabcolumnauth/get_page_protablecolumns_by_authid',
        payload: params,
    });
};


previewItem = id => {
    router.push(`/profile/basic/${id}`);
};

handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
        formValues: {},
    });
    dispatch({
        type: 'protabcolumnauth/query_page_for_proauthority',
        payload: {},
    });
};

toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
        expandForm: !expandForm,
    });
};


handleSelectTableColumnByAuthId = rows => {
	const { dispatch } = this.props;
	const authArray = new Array();
  	rows.map(item => {
		authArray.push(item.auth_id)
		return authArray
	})
  	this.setState({
        selectedRows: rows,
        authId:authArray,
        pageByauthId: rows[0].auth_id,
   	});
	dispatch({
        type: 'protabcolumnauth/get_page_protablecolumns_by_authid', 
        payload: {
        	auth_id:authArray,
        }
 	});
};

handleSelectAuthByTableColumnId = rows => {
  	this.setState({
        selectedRows: rows,
   });
};
handleTableColumnAuthVisible = flag => {
    this.setState({
        tableColumnAuthVisible: !!flag,
    });
};

handleTableColumnList = (flag) => {
	const { formValues } = this.state;
	const { dispatch } = this.props;
	const { authId } = this.state;
	if(!authId || authId.length == 0) {
		message.warning("请选择要授权的角色!!!");
		return false;
	}
	dispatch({
        type: 'protabcolumnauth/query_page_for_protablecolumnchild',
    });
    
	dispatch({
        type: 'protabcolumnauth/get_selected_protablecolumn_by_authid',
        payload: {
        	auth_id: authId
        }
    });
    this.handleTableColumnAuthVisible(flag);
};

handleTableColumnAuthConnect = tableColumnId => {
	const { authId } = this.state;
	const tableColumnAuth = new Array();
	const { dispatch } = this.props;
	if(!authId || authId.length == 0 ) {
		message.warning("请选择要授权的角色!!!");
		return false;
	}
	const authIds = new Array();
	for(let i = 0;i < authId.length;i++) {
		authIds.push({
			id: authId[i]
		})
		for(let j = 0;j < tableColumnId.length;j++) {
			tableColumnAuth.push({
				auth_id: authId[i],
				column_id: tableColumnId[j],
			})
		}
	}
	dispatch({
        type: 'protabcolumnauth/insert_batch_for_protabcolumnauth',
        payload: {
        	authids:authIds,
        	authids_columnids: tableColumnAuth
        }
   	});
   	message.success('授权成功');
	this.handleTableColumnAuthVisible();
};

handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
        if (err) return;

    const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
    };

    this.setState({
        formValues: values,
    });

    dispatch({
        type: 'protabcolumnauth/query_page_for_proauthority',
        payload: values,
    });
});
};

handleModalVisible = flag => {
    this.setState({
        modalVisible: !!flag,
    });
};

handleUpdateModalVisible = (flag, record) => {
    this.setState({
        updateModalVisible: !!flag,
        updateFormValues: record || {},
    });
};

handleViewModalVisible = (flag, record) => {
    this.setState({
        viewModalVisible: !!flag,
        viewFormValues: record || {},
    });
};	

renderAdvancedForm() {
    const {
        form: { getFieldDecorator },
    } = this.props;
    return (
        <Form onSubmit={this.handleSearch} layout="inline">
        	<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
				<Col md={8} sm={24}>
			        <FormItem label="角色名称">
			        {getFieldDecorator('auth_name')(<Input placeholder="请输入" />)}
					</FormItem>
		    	</Col>
				<Col md={8} sm={24}>
			        <FormItem label="角色类型">
			        {getFieldDecorator('auth_type')(<Input placeholder="请输入" />)}
					</FormItem>
		    	</Col>
    		</Row>
		    <div style={{ overflow: 'hidden' }}>
				<div style={{ marginBottom: 24 }}>
					<Button type="primary" htmlType="submit">
			        查询
			        </Button>
			        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
			        重置
			        </Button>
		        	<a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
		        		收起 <Icon type="up" />
		        	</a>
		        </div>
		    </div>
        </Form>
	);
}
renderSimpleForm() {
    const {
        form: { getFieldDecorator },
    } = this.props;
    return (
        <Form onSubmit={this.handleSearch} layout="inline">
        	<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
				<Col md={8} sm={24}>
				    <FormItem label="角色名称">
				        {getFieldDecorator('auth_name')(<Input placeholder="请输入" />)}
					</FormItem>
				</Col>
    			<Col md={8} sm={24}>
			        <FormItem label="角色类型">
			        {getFieldDecorator('auth_type')(<Input placeholder="请输入" />)}
					</FormItem>
		    	</Col>
			    <Col md={8} sm={24}>
			        <span className={styles.submitButtons}>
				        <Button type="primary" htmlType="submit">
				        查询
				        </Button>
				        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
				        重置
				        </Button>
				        <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
				        展开 <Icon type="down" />
				        </a>
			        </span>
			    </Col>
        </Row>
        </Form>
	);
}

    renderForm() {
        const { expandForm } = this.state;
        return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
    }

    render() {
        const {
            protabcolumnauth: { data,tableColumn,tableColumnChild,tableColumnSelect },
            loading,
        } = this.props;

        const { selectedRows, modalVisible, updateModalVisible, viewModalVisible,  updateFormValues,  viewFormValues,tableColumnAuthVisible  } = this.state;
        
        const tabelColumnAuthMethods = {
            handleTableColumnAuthVisible: this.handleTableColumnAuthVisible,
            handleTableColumnAuthConnect: this.handleTableColumnAuthConnect,
            tableColumnSelect: tableColumnSelect,
        };
        return (
            <PageHeaderWrapper title="角色字段信息列表">
            <Card bordered={false}>
            <div className={styles.proUserGrouptableList}>
            <div className={styles.proUserGrouptableListForm}>{this.renderForm()}</div>
            <div className={styles.proUserGrouptableListOperator}>
    	<Button icon="plus" type="primary" onClick={() => this.handleTableColumnList(true)}>
        分配模型列
        </Button>
    </div>
    	<StandardTableAuth
        rowKey={"auth_id"}
        selectedRows={selectedRows}
        loading={loading}
        data={data}
        columns={this.columnsAuth}
        onSelectRow={this.handleSelectTableColumnByAuthId}
        onChange={this.handleStandardTableChangeAuth}
        />
        <StandardTableColumn
        rowKey={"tablecolumn_id"}
        selectedRows={selectedRows}
        loading={loading}
        data={tableColumn}
        columns={this.columnsTable}
        onSelectRow={this.handleSelectAuthByTableColumnId}
        onChange={this.handleStandardTableChangeTableColumn}
        />
        </div>
        </Card>
		<TableColumnAuthModel {...tabelColumnAuthMethods} tableColumnAuthVisible={ tableColumnAuthVisible } tableColumnChild={ tableColumnChild }/>
    </PageHeaderWrapper>
    );
    }
}

export default ProTableColumnAuthList;
